package com.box.ai.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.box.ai.mapper.GameChatMapper;
import com.box.ai.mapper.PdfChatMapper;
import com.box.ai.pojo.entity.GameChat;
import com.box.ai.pojo.entity.PdfChat;
import com.box.ai.pojo.enums.ChatTypeEnum;
import com.box.ai.pojo.vo.MessageVO;
import com.box.ai.service.handler.ChatTypeHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class PdfChatServiceImpl extends ServiceImpl<PdfChatMapper, PdfChat> implements ChatTypeHandler {

    private final PdfChatMapper pdfChatMapper;
    private final ChatMemory chatMemory;

    @Override
    public ChatTypeEnum geByType() {
        return ChatTypeEnum.PDF_CHAR;
    }

    @Override
    public List<String> queryByType(String type) {
        LambdaQueryWrapper<PdfChat> typeQuery = new LambdaQueryWrapper<>();
        typeQuery.eq(PdfChat::getType,type);
        List<PdfChat> typeList = pdfChatMapper.selectList(typeQuery);
        if (CollectionUtils.isEmpty(typeList)){
            return Collections.emptyList();
        }
        List<String> chatIds = typeList.stream().map(PdfChat::getChatId).collect(Collectors.toList());
        return chatIds;
    }

    @Override
    public void saveChat(String chat, String chatId) {
        PdfChat type = new PdfChat();
        type.setType(chat);
        type.setChatId(chatId);
        LambdaQueryWrapper<PdfChat> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PdfChat::getChatId,chatId)
                        .eq(PdfChat::getType,chat);
        List<PdfChat> types = pdfChatMapper.selectList(queryWrapper);
        if (types.isEmpty()){
            pdfChatMapper.insert(type);
        }
    }

    @Override
    public List<MessageVO> getHistoryChat(String type, String chatId) {
        List<Message> messages = chatMemory.get(chatId, Integer.MAX_VALUE);
        if (CollectionUtils.isEmpty(messages)){
            //TODO:后续改成记忆内容从redis中查询，这里如果为空既要先从数据库中查询
            return Collections.emptyList();
        }
        List<MessageVO> messageVOS = new ArrayList<>();
        for (Message message : messages) {
            MessageVO messageVO = new MessageVO(message);
            messageVOS.add(messageVO);
        }
        return messageVOS;
    }
}
